<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="header-left">
          <view class="back-btn" @tap="goBack">
            <text class="back-icon">←</text>
          </view>
          <text class="header-title">收货地址</text>
        </view>
        <view class="header-right">
          <view class="add-btn" @tap="handleAddAddress">
            <text class="add-icon">+</text>
            <text class="add-text">新增地址</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 地址列表 -->
    <scroll-view class="address-scroll" scroll-y="true">
      <view v-if="addresses.length === 0" class="empty-address">
        <text class="empty-icon">📍</text>
        <text class="empty-text">还没有收货地址</text>
        <view class="add-address-btn" @tap="handleAddAddress">
          <text class="btn-text">添加收货地址</text>
        </view>
      </view>

      <view v-else class="address-list">
        <view v-for="address in addresses" :key="address.id" class="address-item">
          <view class="address-content">
            <view class="address-header">
              <view class="user-info">
                <text class="user-name">{{ address.name }}</text>
                <text class="user-phone">{{ address.phone }}</text>
              </view>
              <view class="address-tags">
                <view v-if="address.isDefault" class="default-tag">默认</view>
                <view class="type-tag">{{ address.tag }}</view>
              </view>
            </view>

            <view class="address-detail">
              <text class="address-text">{{ address.detail }}</text>
            </view>
          </view>

          <view class="address-actions">
            <view v-if="!address.isDefault" class="action-btn" @tap="setDefault(address.id)">
              <text class="action-text">设为默认</text>
            </view>
            <view class="action-btn" @tap="editAddress(address)">
              <text class="action-icon">✏️</text>
              <text class="action-text">编辑</text>
            </view>
            <view class="action-btn delete-btn" @tap="deleteAddress(address.id)">
              <text class="action-icon">🗑️</text>
              <text class="action-text">删除</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 添加/编辑地址弹窗 -->
    <view v-if="showAddressModal" class="modal-overlay" @tap="closeModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingAddress ? '编辑地址' : '新增地址' }}</text>
          <view class="close-btn" @tap="closeModal">
            <text class="close-icon">×</text>
          </view>
        </view>

        <scroll-view class="modal-body" scroll-y="true">
          <view class="form-group">
            <view class="form-row">
              <view class="form-item">
                <text class="form-label">收货人 *</text>
                <input class="form-input" v-model="formData.name" placeholder="请输入收货人姓名" maxlength="20" />
              </view>
              <view class="form-item">
                <text class="form-label">手机号 *</text>
                <input class="form-input" v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" />
              </view>
            </view>
          </view>

          <view class="form-group">
            <text class="form-label">所在地区 *</text>
            <view class="region-selector">
              <picker mode="multiSelector" :value="regionIndex" :range="regionData" @change="onRegionChange">
                <view class="region-display">
                  <text class="region-text">{{ formData.province || '省份' }} {{ formData.city || '城市' }} {{ formData.district || '区县' }}</text>
                  <text class="arrow-icon">→</text>
                </view>
              </picker>
            </view>
          </view>

          <view class="form-group">
            <text class="form-label">详细地址 *</text>
            <textarea class="form-textarea" v-model="formData.detail" placeholder="请输入详细地址（街道、门牌号等）" maxlength="100" auto-height />
          </view>

          <view class="form-group">
            <text class="form-label">地址标签</text>
            <view class="tag-selector">
              <view v-for="tag in addressTags" :key="tag" class="tag-item" :class="{ active: formData.tag === tag }" @tap="selectTag(tag)">
                <text class="tag-text">{{ tag }}</text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="modal-footer">
          <view class="footer-btn cancel-btn" @tap="closeModal">
            <text class="btn-text">取消</text>
          </view>
          <view class="footer-btn confirm-btn" :class="{ disabled: !isFormValid }" @tap="saveAddress">
            <text class="btn-text">保存</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const BASE_URL = getApp().$vm.$global.baseURL

export default {
  data() {
    return {
      addresses: [],
      showAddressModal: false,
      editingAddress: null,
      formData: {
        name: '', phone: '', province: '', city: '', district: '', detail: '', tag: '家'
      },
      addressTags: ['家', '公司', '学校', '其他'],
      regionIndex: [0, 0, 0],
      regionData: [['福建省', '广东省', '浙江省'], ['南平市', '福州市', '厦门市'], ['武夷山市', '鼓楼区', '台江区']],
      fromCheckout: false
    }
  },

  computed: {
    isFormValid() {
      return this.formData.name && this.formData.phone && this.formData.province && this.formData.city && this.formData.district && this.formData.detail
    }
  },

  onLoad(options) {
    if (options.from === 'checkout') this.fromCheckout = true
    this.fetchAddressList()
  },

  methods: {
    goBack() {
      this.fromCheckout ? uni.navigateBack() : uni.switchTab({ url: '/pages/profile/profile' })
    },

    fetchAddressList() {
      const userInfo = uni.getStorageSync('userInfo') || {}
      const userId = userInfo.id
      if (!userId) return

      uni.request({
        url: `${BASE_URL}/api/address/${userId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === '200') {
            this.addresses = res.data.data.map(item => ({
              id: item.id,
              name: item.linkUser,
              phone: item.linkPhone,
              detail: item.linkAddress,
              province: '', city: '', district: '',
              tag: '其他',
              isDefault: false
            }))
          }
        }
      })
    },

    handleAddAddress() {
      this.editingAddress = null
      this.formData = { name: '', phone: '', province: '', city: '', district: '', detail: '', tag: '家' }
      this.regionIndex = [0, 0, 0]
      this.showAddressModal = true
    },

    editAddress(address) {
      this.editingAddress = address
      this.formData = {
        name: address.name,
        phone: address.phone,
        detail: address.detail,
        province: '', city: '', district: '',
        tag: address.tag
      }
      this.showAddressModal = true
    },

    closeModal() {
      this.showAddressModal = false
      this.editingAddress = null
    },

    selectTag(tag) {
      this.formData.tag = tag
    },

    onRegionChange(e) {
      const values = e.detail.value
      this.regionIndex = values
      this.formData.province = this.regionData[0][values[0]]
      this.formData.city = this.regionData[1][values[1]]
      this.formData.district = this.regionData[2][values[2]]
    },

    saveAddress() {
      if (!this.isFormValid) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' })
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
        return
      }

      const userInfo = uni.getStorageSync('userInfo') || {}
      const userId = userInfo.id
      if (!userId) return

      const payload = {
        linkUser: this.formData.name,
        linkPhone: this.formData.phone,
        linkAddress: `${this.formData.province} ${this.formData.city} ${this.formData.district} ${this.formData.detail}`,
        userId
      }

      if (this.editingAddress) {
        payload.id = this.editingAddress.id
        uni.request({
          url: `${BASE_URL}/api/address`,
          method: 'PUT',
          data: payload,
          success: (res) => {
            if (res.data.code === '200') {
              uni.showToast({ title: '地址修改成功', icon: 'success' })
              this.fetchAddressList()
              this.closeModal()
            }
          }
        })
      } else {
        payload.id = 0
        uni.request({
          url: `${BASE_URL}/api/address`,
          method: 'POST',
          data: payload,
          success: (res) => {
            if (res.data.code === '200') {
              uni.showToast({ title: '地址添加成功', icon: 'success' })
              this.fetchAddressList()
              this.closeModal()
            }
          }
        })
      }
    },

    deleteAddress(id) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该地址吗？',
        confirmText: '删除',
        confirmColor: '#ff4757',
        success: (res) => {
          if (res.confirm) {
            uni.request({
              url: `${BASE_URL}/api/address/${id}`,
              method: 'DELETE',
              success: (res) => {
                if (res.data.code === '200') {
                  uni.showToast({ title: '删除成功', icon: 'success' })
                  this.fetchAddressList()
                }
              }
            })
          }
        }
      })
    },

    setDefault(id) {
      this.addresses.forEach(addr => addr.isDefault = addr.id === id)
      uni.showToast({ title: '已设为默认地址', icon: 'success' })
    }
  }
}
</script>



<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航 */
.header {
  background-color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 50;
}

.header-content {
  max-width: 750rpx;
  margin: 0 auto;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-btn {
  padding: 10rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  padding: 16rpx 24rpx;
  border-radius: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(56, 143, 74, 0.3);
}

.add-icon {
  font-size: 24rpx;
  font-weight: bold;
}

.add-text {
  font-size: 24rpx;
}

/* 地址列表 */
.address-scroll {
  height: calc(100vh - 120rpx);
  /* padding: 30rpx; */
}

.empty-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 60rpx;
}

.add-address-btn {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  padding: 24rpx 60rpx;
  border-radius: 50rpx;
  box-shadow: 0 8rpx 20rpx rgba(56, 143, 74, 0.3);
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.address-item {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.address-content {
  padding: 30rpx;
}

.address-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.user-phone {
  font-size: 24rpx;
  color: #666;
}

.address-tags {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.default-tag {
  background-color: #388f4a;
  color: white;
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.type-tag {
  background-color: #f0f0f0;
  color: #666;
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.address-detail {
  margin-bottom: 20rpx;
}

.address-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 30rpx;
  padding: 20rpx 30rpx;
  background-color: #f8f9fa;
  border-top: 1rpx solid #e9ecef;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  background-color: white;
  border: 1rpx solid #e9ecef;
}

.action-btn:active {
  transform: scale(0.95);
}

.delete-btn {
  border-color: #ff4757;
}

.delete-btn .action-text {
  color: #ff4757;
}

.action-icon {
  font-size: 20rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-height: 100vh;
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  padding: 10rpx;
}

.close-icon {
  font-size: 40rpx;
  color: #999;
}

.modal-body {
  max-height: 60vh;
  overflow-y: auto; /* ✅ 添加滚动 */
  padding: 30rpx;
  width: auto;
}


.form-group {
  margin-bottom: 30rpx;
}

/* 解决手机号换行问题 */
.form-row {
  display: flex;
  flex-wrap: wrap; /* ✅ 允许换行 */
  gap: 20rpx;
}

.form-item {
  flex: 1 1 100%; /* ✅ 每个输入项占据整行，在小屏自动换行 */
}


.form-label {
  padding: 0 45rpx;
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 26rpx;
  background-color: #f8f9fa;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 26rpx;
  background-color: #f8f9fa;
}

.region-selector {
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  background-color: #f8f9fa;
}

.region-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
}

.region-text {
  font-size: 26rpx;
  color: #333;
}

.arrow-icon {
  font-size: 24rpx;
  color: #999;
}

.tag-selector {
  display: flex;
  gap: 20rpx;
  flex-wrap: wrap;
}

.tag-item {
  padding: 16rpx 24rpx;
  border: 1rpx solid #e9ecef;
  border-radius: 20rpx;
  background-color: #f8f9fa;
}

.tag-item.active {
  background-color: #388f4a;
  border-color: #388f4a;
}

.tag-item.active .tag-text {
  color: white;
}

.tag-text {
  font-size: 24rpx;
  color: #666;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #e9ecef;
}

.footer-btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 12rpx;
  text-align: center;
}

.cancel-btn {
  background-color: #f8f9fa;
  border: 1rpx solid #e9ecef;
}

.confirm-btn {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
}

.confirm-btn.disabled {
  background: #ccc;
}

.btn-text {
  font-size: 28rpx;
  font-weight: 500;
}

.cancel-btn .btn-text {
  color: #666;
}

.confirm-btn .btn-text {
  color: white;
}
</style>
